﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
using InkjetControl.NLog;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace InkjetControl.codec.codes
{
    public class MessageDecoder : ByteToMessageDecoder
    {
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
        {
            Message msg = new()
            {
                // 魔数
                MagicNumber = input.ReadInt(),
                // 主版本号
                MainVersion = input.ReadByte(),
                // 次版本号
                SubVersion = input.ReadByte(),
                // 修订版本号
                ModifyVersion = input.ReadByte(),
                // 会话ID
                SessionId = input.ReadLong(),
                // 消息类型
                MessageType = (MessageType)Enum.ToObject(typeof(MessageType), input.ReadByte())
            };

            int mclen = input.ReadInt();
            if (mclen > 0)
            {
                msg.MachineCode = input.ReadString(mclen, Encoding.UTF8);
               
            }

            int mlLen = input.ReadInt();
            if (mlLen > 0)
            {
                msg.MachineLabel = input.ReadString(mlLen, Encoding.UTF8);
            }

            // 消息体大小
            int bodySize = input.ReadInt();

            if (bodySize > 0)
            {
                string bodyJson;
                //Log.Logger.Debug("MessageDecoder bodySize:{0}", bodySize);
                //string bodyJson = input.ReadString(bodySize, Encoding.UTF8);
                byte[] bodyBytes = new byte[bodySize];
                input.ReadBytes(bodyBytes);
                bodyJson = Encoding.UTF8.GetString(bodyBytes);
                if (bodyJson != null)
                {
                    msg.Body = JsonConvert.DeserializeObject<Body<object>>(bodyJson);

                }
            }
            output.Add(msg);
        }

    }
}
